package com.yuanli.card.manage.controller;

import com.github.pagehelper.PageInfo;
import com.yuanli.card.authentication.service.ISysUserService;
import com.yuanli.card.manage.service.OutStoreService;
import com.yuanli.card.pojo.OutStore;
import com.yuanli.card.pojo.SysUser;
import com.yuanli.card.req.OutStoreQueryReq;
import com.yuanli.card.res.ResponseBean;
import com.yuanli.card.utils.JsonMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/outStore")
public class OutStoreController {
    @Resource
    private OutStoreService outStoreService;
    @Resource
    private ISysUserService sysUserService;

    @GetMapping("/query")
    public ResponseBean query(OutStoreQueryReq req) {
        Map<String, Object> data = new HashMap<>();
        req.setCustomerId(sysUserService.currentUser().getId().intValue());
        PageInfo<OutStore> pageInfo = outStoreService.query(req);
        data.put("total", pageInfo.getTotal());
        data.put("list", this.fillOutStore(pageInfo.getList()));
        return ResponseBean.success().setData(data);
    }

    @PostMapping("/send")
    public ResponseBean send(Integer id){
        outStoreService.updateStatus(id,1);
        return ResponseBean.success();
    }

    private List<Map<String, Object>> fillOutStore(List<OutStore> list) {
        if (list == null) {
            return null;
        }
        return list.parallelStream().map(outStore -> {
            Map<String, Object> map = JsonMapper.defaultMapper().json2Map(JsonMapper.defaultMapper().toJson(outStore));
            SysUser user = sysUserService.findById(outStore.getSaleCustomerId().longValue());
            map.put("customerName",user==null?null:user.getNickname());
            return map;
        }).collect(Collectors.toList());
    }
}
